<template>
  <div>
    <div
        v-if="number > 0"
        class="order-reminder-panel"
        :style="{ right: panelPosition.right + 'px', bottom: panelPosition.bottom + 'px' }"
        @mousedown="startDrag"
    >
      <div class="panel-header">
        <span style="font-size: 20px">订单下载提醒（{{ number }}）</span>
        <span class="hint-text">下载完所有提醒订单后弹窗消失</span>
      </div>
      <div class="panel-body">
        <div
            v-for="(order, index) in orders.slice(0, 5)"
            :key="index"
            class="order-item"
        >
          <div class="order-info">
            <div class="file-identifier">文件标识：{{ order.fileName }}</div>
            <div class="reminder-info">
              <span>{{ order.createTime }}</span>
              <el-button v-hasPerm="['system:lpsOrder:download']" type="primary" link @click="downloadOrder(order)" style="margin-right: 10px">立即下载</el-button>
            </div>
          </div>
        </div>
      </div>
      <div class="panel-footer">
        <el-button type="primary" link @click="showMoreOrders">>>查看更多</el-button>
      </div>
    </div>

    <!-- 查看更多弹窗 -->
    <el-dialog
        v-model="moreDialog.visible"
        title="订单下载提醒"
        width="75%"
        @close="handleCloseMoreDialog"
        :close-on-click-modal="false"
    >
      <div class="search-bar">
        <el-form :model="moreQueryParams" :inline="true">
          <el-form-item label="提醒时间">
            <el-date-picker
                v-model="moreQueryParams.createTime"
                type="daterange"
                class="!w-[250px]"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="用户名称">
            <el-input
                v-model="moreQueryParams.userName"
                placeholder="用户名称"
                clearable
                @keyup.enter="handleQueryMore"              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="文件标识">
            <el-input
                v-model="moreQueryParams.fileName"
                placeholder="文件标识"
                clearable
                @keyup.enter="handleQueryMore"              style="width: 200px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQueryMore">
              <template #icon>
                <Search />
              </template>
              搜索
            </el-button>
            <el-button @click="handleResetQueryMore">
              <template #icon>
                <Refresh />
              </template>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table
          v-loading="moreLoading"
          :data="morePageData"
          highlight-current-row
          border
      >
        <el-table-column type="index" label="序号" width="70" align="center" />
        <el-table-column
            key="remindTime"
            label="提醒时间"
            prop="remindTime"
            width="200"
            align="center"
        />
        <el-table-column label="下载标识" width="120" align="center">
          <template #default="scope">
            <DictLabel v-model="scope.row.isDownload" code="is_download" />
          </template>
        </el-table-column>
        <el-table-column
            key="fileName"
            label="文件标识"
            prop="fileName"
            min-width="300"
            align="center"
            :show-overflow-tooltip="true"
        />
        <el-table-column
            key="userName"
            label="用户名称"
            prop="userName"
            width="200"
            align="center"
            :show-overflow-tooltip="true"
        />
        <el-table-column
            key="deptName"
            label="部门名称"
            prop="deptName"
            min-width="200"
            align="center"
            :show-overflow-tooltip="true"
        />
        <el-table-column fixed="right" label="操作" width="100" align="center">
          <template #default="scope">
            <el-button
                v-hasPerm="['system:lpsOrder:download']"
                type="primary"
                size="small"
                link
                @click="downloadOrder(scope.row)"
            >
              下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-if="moreTotal > 0"
          v-model:total="moreTotal"
          v-model:page="moreQueryParams.pageNum"
          v-model:limit="moreQueryParams.pageSize"
          @pagination="handleQueryMore"
      />

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseMoreDialog">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">import { useStomp } from "@/hooks/useStomp";
import { useUserStoreHook } from "@/store/modules/user";
import { reactive, ref } from "vue";
import LpsOrderDownloadAPI, { LpsOrderDownloadPageQuery, LpsOrderDownloadPageVO } from "@/api/system/lps-order-download";
import LpsOrderAPI, { LpsOrderPageQuery } from "@/api/system/lps-order";
import { Search, Refresh } from "@element-plus/icons-vue";

const userStore = useUserStoreHook();
// 用于手动调整 WebSocket 地址
const socketEndpoint = ref(import.meta.env.VITE_APP_WS_ENDPOINT);
// 同步连接状态
interface MessageType {
  type?: string;
  sender?: string;
  content: string;
}
const messages = ref<MessageType[]>([]);
// 广播消息内容
const topicMessage = ref("亲爱的朋友们，系统已恢复最新状态。");
// 点对点消息内容（默认示例）
const queneMessage = ref("Hi, " + userStore.userInfo.username + " 这里是点对点消息示例！");
const receiver = ref("root");

const panelPosition = reactive({
  right: 0,
  bottom: 0
});

let isDragging = false;
let dragOffset = { x: 0, y: 0 };

const startDrag = (e: MouseEvent) => {
  isDragging = true;
  dragOffset.x = e.clientX - (window.innerWidth - panelPosition.right);
  dragOffset.y = e.clientY - (window.innerHeight - panelPosition.bottom);

  document.addEventListener('mousemove', onDrag);
  document.addEventListener('mouseup', stopDrag);
};

const onDrag = (e: MouseEvent) => {
  if (!isDragging) return;

  let newRight = window.innerWidth - e.clientX + dragOffset.x;
  let newBottom = window.innerHeight - e.clientY + dragOffset.y;

  panelPosition.right = Math.max(0, newRight);
  panelPosition.bottom = Math.max(0, newBottom);
};

const stopDrag = () => {
  isDragging = false;
  document.removeEventListener('mousemove', onDrag);
  document.removeEventListener('mouseup', stopDrag);
};

const number = ref(0);
const orders = ref<LpsOrderDownloadPageVO[]>([]);

// 查看更多弹窗相关数据
const moreDialog = reactive({
  visible: false
});

const moreLoading = ref(false);
const moreTotal = ref(0);
const morePageData = ref<LpsOrderDownloadPageVO[]>([]);

const moreQueryParams = reactive<LpsOrderDownloadPageQuery>({
  pageNum: 1,
  pageSize: 10,
  isDownload: 0
});

const orderQueryParams = reactive<LpsOrderPageQuery>({
  pageNum: 1,
  pageSize: 10
});

// 显示更多订单弹窗
const showMoreOrders = () => {
  moreDialog.visible = true;
  // 初始化查询
  handleQueryMore();
};

// 查询更多订单数据
const handleQueryMore = () => {
  moreLoading.value = true;
  LpsOrderDownloadAPI.getPage(moreQueryParams)
      .then((data) => {
        morePageData.value = data.list;
        moreTotal.value = data.total;
      })
      .finally(() => {
        moreLoading.value = false;
      });
};

// 重置查询条件
const handleResetQueryMore = () => {
  moreQueryParams.createTime = undefined;
  moreQueryParams.userName = undefined;
  moreQueryParams.fileName = undefined;
  moreQueryParams.pageNum = 1;
  handleQueryMore();
};

// 关闭查看更多弹窗
const handleCloseMoreDialog = () => {
  moreDialog.visible = false;
  morePageData.value = [];
  moreTotal.value = 0;
  moreQueryParams.pageNum = 1;
  moreQueryParams.pageSize = 10;
  moreQueryParams.createTime = undefined;
  moreQueryParams.userName = undefined;
  moreQueryParams.fileName = undefined;
};

const downloadOrder = (order: LpsOrderDownloadPageVO) => {
  console.log(`Downloading order: ${order.id}`);
  orderQueryParams.ids = order.orderId + "";

  LpsOrderAPI.downloadByIds(orderQueryParams).then((response: any) => {
    const fileData = response.data;

    // 从 Content-Disposition 中提取文件名
    const disposition = response.headers["content-disposition"];
    let fileName = "莱普森订单.zip";
    if (disposition && disposition.indexOf("filename=") !== -1) {
      fileName = decodeURIComponent(
          disposition
              .split("filename=")[1]
              .split(";")[0]
              .replace(/UTF-8''/i, "")
              .trim()
      );
    }

    // 使用正确的 MIME 类型 application/zip
    const blob = new Blob([fileData], { type: "application/zip" });
    const downloadUrl = window.URL.createObjectURL(blob);

    const downloadLink = document.createElement("a");
    downloadLink.href = downloadUrl;
    downloadLink.download = fileName;
    document.body.appendChild(downloadLink);
    downloadLink.click();

    document.body.removeChild(downloadLink);
    window.URL.revokeObjectURL(downloadUrl);

    // 下载完成后更新提醒数量
    // number.value = Math.max(0, number.value - 1);
    ElMessage.success("下载成功");
    handleResetQueryMore();
  });
};
// 监听 number.value 的变化，当值小于等于1时关闭查看更多弹窗
watch(
    () => number.value,
    (newVal) => {
      if (newVal <= 0) {
        handleCloseMoreDialog()
      }
    }
);


// 调用 useStomp hook，默认使用 socketEndpoint 和 token（此处用 getAccessToken()）
const { isConnected, connect, subscribe, disconnect, client } = useStomp({
  debug: true,
});

watch(
    () => isConnected.value,
    (connected) => {
      if (connected) {
        // 连接成功后，订阅广播和点对点消息主题
        subscribe("/topic/notice", (res) => {
          messages.value.push({
            sender: "Server",
            content: res.body,
          });
        });
        subscribe("/user/queue/greeting", (res) => {
          const messageData = JSON.parse(res.body) as MessageType;
          messages.value.push({
            sender: messageData.sender,
            content: messageData.content,
          });
          number.value = parseInt(messageData.content, 10);
          if (number.value > 0) {
            LpsOrderDownloadAPI.getPage(moreQueryParams)
                .then((data) => {
                  orders.value = data.list;
                  number.value = data.total;
                });
            ElNotification({
              title: '下载提醒',
              dangerouslyUseHTMLString: true,
              message: '<div style="font-size: 15px;">您有未及时下载的订单 请及时处理</div>',
              type: 'warning',
              duration: 5000,
            })
          }
        });
        messages.value.push({
          sender: "Server",
          content: "Websocket 已连接",
          type: "tip",
        });
      } else {
        messages.value.push({
          sender: "Server",
          content: "Websocket 已断开",
          type: "tip",
        });
      }
    }
);

const queryParams = reactive<LpsOrderDownloadPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 连接 WebSocket
function connectWebSocket() {
  connect();
}

// 断开 WebSocket
function disconnectWebSocket() {
  disconnect();
}

// 发送广播消息
function sendToAll() {
  if (client.value && client.value.connected) {
    client.value.publish({
      destination: "/topic/notice",
      body: topicMessage.value,
    });
    messages.value.push({
      sender: userStore.userInfo.username,
      content: topicMessage.value,
    });
  }
}

if (onMounted) {
  onMounted(() => {
    connectWebSocket();
  });
}

if (onBeforeUnmount) {
  onBeforeUnmount(() => {
    disconnectWebSocket();
  });
}
</script>

<style scoped lang="scss">.order-reminder-panel {
  position: fixed;
  width: 470px;
  background: #fff;
  z-index: 1000;
  cursor: move;
  display: flex;
  flex-direction: column;
  max-height: 80vh;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .panel-header {
    padding: 2px 2px 2px 10px;
    background: #2285ec;
    border-bottom: 1px solid #ddd;
    display: flex;
    flex-direction: column;
    color: #fff;
    font-size: 18px;
    font-weight: bold;

    .hint-text {
      color: gold;
      font-size: 12px;
    }
  }

  .panel-body {
    padding: 2px 2px 2px 10px;

    .order-item {
      border-bottom: 1px solid #ddd;

      .order-info {
        display: flex;
        flex-direction: column;

        .file-identifier {
          padding: 2px 2px;
          color: #333;
          font-size: 14px;
          word-wrap: break-word;
          word-break: break-all;
        }

        .reminder-info {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 2px 2px;

          span {
            color: #333;
            font-size: 14px;
          }
        }
      }
    }
  }

  .panel-footer {
    padding: 10px;
    text-align: left;
    background: #ffffff;
  }
}
</style>